﻿(function(mt, $, undefined) {

	mt.runBackgroundSlider = function() {
		var backgroundImages = [$('#mt-bg-1'), $('#mt-bg-2'), $('#mt-bg-3')];
		window.setTimeout(function() {
			backgroundImages[0].animate({ opacity: 0 }, 5000);
			backgroundImages[1].animate({ opacity: 1 }, 5000);
		}, 5000);
		var index = 1;
		window.setInterval(function() {
			backgroundImages[index % 3].animate({ opacity: 0 }, 5000);
			backgroundImages[(index + 1) % 3].animate({ opacity: 1 }, 5000);
			index++;
		}, 20000);
	};

	mt.hideStep2 = function(hide) {
		var selector = '#webform-component-firstname, #webform-component-surename, #webform-component-email, #edit-actions, #calculated-price, #webform-component-adult-count, #webform-component-price-included, #webform-component-phone, #webform-component-bed-count';
		hide ? $(selector).hide() : $(selector).show();
	};

	mt.collect = function(op) {
		return {
			arrival: getArrival(),
			departure: getDeparture(),
			accomodation: $('#edit-submitted-accomodation input:checkbox:checked').map(function(){ return $(this).val(); }).get().join(),
			adultCount: $('#edit-submitted-adult-count option:selected').val(),
			bedCount: $('#edit-submitted-bed-count option:selected').val(),
			lang: lang(),
			op: op
		};
	};

	mt.showError = function(e) {
		if (e.e.length) {
			createErrorMessages(e);
		}
		if (e.cal) {
			createOccupationCalendars(e.cal);
		}
	};

	mt.setPrice = function(data) {
		if (data.price) {
			var form = mt.collect();
			var textTemplate = $('#webform-component-calculated-price-template').html();
			textTemplate = textTemplate.replace('{0}', '<span id="accomodation-price">' + data.price + '</span>');
			textTemplate = textTemplate.replace('{1}', form.arrival + '&nbsp;&ndash;&nbsp;' + form.departure);
			textTemplate = textTemplate.replace('{2}', data.municipalTaxUnitSpa);
			textTemplate = textTemplate.replace('{3}', data.municipalTaxUnitBed);
			$('#calculated-price').remove();
			$('#webform-component-calculateprice').append('<div id="calculated-price">' + textTemplate + '</div>');
		}
		$('#calculated-municipal-tax').remove();
		if (data.municipalTax) {
			var municipalTaxHtml = $('#webform-component-municipal-tax-template').html().replace('{0}', '<span id="municipal-tax">' + data.municipalTax + '</span>');
			$('#webform-component-bed-count').append('<div id="calculated-municipal-tax">' + municipalTaxHtml + '</div>');
		}
	};

	mt.onChangeArrival = function() {
		var arrival = new Date(getArrival());
		var departure = new Date(getDeparture());
		if (arrival < departure) return;
		
		var newDeparture = new Date(arrival.getTime() + 604800000);
		$('#edit-submitted-departure-year').val(newDeparture.getFullYear());
		$('#edit-submitted-departure-month').val(newDeparture.getMonth() + 1);
		$('#edit-submitted-departure-day').val(newDeparture.getDate());
	};
	
	mt.setArrivalOnSelect = function() {
		$('#edit-submitted-arrival-year, #edit-submitted-arrival-month, #edit-submitted-arrival-day').change(mt.onChangeArrival);
		var elCal = $('#webform-component-arrival input.webform-calendar');
		if (elCal.length) {
			var originalOnSelect = elCal.datepicker("option", "onSelect");
			var onSelect = function(dateText, inst) {
				originalOnSelect(dateText, inst);
				mt.onChangeArrival();
			};
			$('#webform-component-arrival input.webform-calendar').datepicker("option", "onSelect", onSelect);
		}
	};

	mt.ml = function() {
		var s1 = 'jnfo'; var s2 = 'montanus'; var s3 = 'cz';
		var result = s1 + String.fromCharCode(64) + s2 + String.fromCharCode(46) + s3;
		return String.fromCharCode(result.charCodeAt(0) - 1) + result.substring(1);
	};
	
	function lang() {
		var classList = $('body').attr('class').split(/\s+/);
		for (var i = 0; i < classList.length; i++) {
			var cls = classList[i];
			if (cls.indexOf('i18n-') == 0) {
				return cls.substring(5);
			}
		}
		return 'cs';
	};

	function getArrival() {
		return $('#edit-submitted-arrival-year').val() + '/' + $('#edit-submitted-arrival-month option:selected').val() + '/' + $('#edit-submitted-arrival-day').val();
	};

	function getDeparture() {
		return $('#edit-submitted-departure-year').val() + '/' + $('#edit-submitted-departure-month option:selected').val() + '/' + $('#edit-submitted-departure-day').val();
	};
	
	function createErrorMessages(e) {
		var html = '<div id="messages"><div class="section clearfix"><div class="messages error"><h2 class="element-invisible">Error message</h2><ul>';
		for (var i = 0; i < e.e.length; i++) {
			html += '<li>';
			html += e.e[i];
			html += '</li>';
		}
		html += '</ul></div></div></div>';
		$('#header').after(html);
	};
	
	function createOccupationCalendars(cal) {
		var html =
			'<div id="mt-occupation-calendars">'
				+ '<table id="mt-occupation-calendars-table">'
					+ '<tr><td>'
						+ '<div><h2>Apartmán Priessnitz</h2><div id="mt-cal-pr" /></div></td><td>'
						+ '<div id="mt-occupation-calendar-kn"><h2>Apartmán Kneipp</h2><div id="mt-cal-kn" /></div></td>'
					+ '</tr>'
					+ '<tr><td colspan="2">'
						+ '<div id="mt-occupation-calendar-ch"><h2>Chata</h2><div id="mt-cal-ch" /></div></td>'
					+ '</tr>'
				+ '</table>'
				+ '<div id="mt-occupation-legend">'
					+ 'Legenda '
					+ '<img src="/sites/all/themes/mybartik/images/legend-free.png" alt="legend free" /> volno '
					+ '<img src="/sites/all/themes/mybartik/images/legend-reserved.png" alt="legend reserved" /> rezervováno '
					+ '<img src="/sites/all/themes/mybartik/images/legend-occupied.png" alt="legend occupied" /> obsazeno'
				+ '</div>'
			+ '</div>';
		$('#webform-component-calculateprice').after(html);
		$('#mt-cal-pr, #mt-cal-kn, #mt-cal-ch').datepicker({dateFormat: 'yy/m/d', defaultDate: getArrival(), beforeShowDay: function(date) {
			var css = getOccupationCalendarCss(date, cal, this.id);
			return [true, css, ''];
		}});
	};
	
	function getOccupationCalendarCss(date, cal, id) {
		var css = 'mt-occupation';
		
		var d = new Date(date);
		d.setDate(date.getDate() - 1);
		var key = $.datepicker.formatDate("yy-mm-dd", d);
		var previous = getOccupationCalendarValue(cal, key, id);
		switch (previous) {
			case 0: css += '-free'; break;
			case 1: css += '-reserved'; break;
			case 2: css += '-occupied'; break;
		}
		
		key = $.datepicker.formatDate("yy-mm-dd", date);
		var current = getOccupationCalendarValue(cal, key, id);
		if (previous == current) return css;
		
		switch (current) {
			case 0: css += '-free'; break;
			case 1: css += '-reserved'; break;
			case 2: css += '-occupied'; break;
		}
		
		return css;
	};
	
	function getOccupationCalendarValue(cal, key, id) {
		var values = cal[key];
		if (values) {
			var acc = id.substring(7);
			return values[acc];
		}
		return 0;
	};

}(window.mt = window.mt || {}, jQuery));

jQuery(document).ready(function ($) {

	$('#mt-ml').text(mt.ml());

	if ($('body.page-node-5').length == 0) {
		mt.runBackgroundSlider();
		return;
	}

	$('#webform-component-calculated-price-template').hide();
	$('#webform-component-municipal-tax-template').hide();

	var calculatePriceText = $('#webform-component-calculateprice p').text();
	$('#webform-component-calculateprice p').remove();
	$('#webform-component-calculateprice').append('<input type="submit" id="calculate-price-submit" class="form-submit" value="' + calculatePriceText + '" />');

	if ($('#messages div.error').length == 0) {
		mt.hideStep2(true);
	}
	else {
		$.post('/price-calculator', mt.collect('accomodation-price'), function(data){
			mt.setPrice(data);
		});
	}

	mt.setArrivalOnSelect();

	$('#edit-submitted-adult-count, #edit-submitted-bed-count').change(function () {
		$.post('/price-calculator', mt.collect('municipal-tax'), function(data){
			mt.setPrice(data);
		});
	});

	$('#calculate-price-submit').click(function() {
		$('#messages').remove();
		$('#mt-occupation-calendars').remove();
		$.post('/price-calculator', mt.collect('accomodation-price'), function(data){
			if (!data) {
				mt.hideStep2(true);
				return;
			}
			if (!data.price) {
				mt.hideStep2(true);
				mt.showError(data);
				return;
			}
			mt.setPrice(data);
			mt.hideStep2(false);
		});
		return false;
	});

	mt.runBackgroundSlider();

});
